﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Caching;

namespace GiaoTrinhEPU.Repositories.Repositories
{
    public class LevelRepository : BaseRepository, ILevelRepository
    {
        public LevelRepository() : base() { }
        public LevelRepository(ICacheProvider cacheProvider) : base(cacheProvider) { }

        /// <summary>
        /// Clear cache of all banks
        /// </summary>
        public void ClearCache()
        {
            Cache.Invalidate("levels");
        }

        /// <summary>
        /// Clear cache of the level
        /// </summary>
        /// <param name="key"></param>
        public void ClearCache(String key)
        {
            Cache.Invalidate("level-" + key);
        }
        /// <summary>
        /// Create a new bank
        /// </summary>
        /// <param name="item"></param>
        public void CreateLevel(Level item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    db.Levels.InsertOnSubmit(item);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }

        // <summary>
        /// Update Level
        /// </summary>
        /// <param name="item"></param>
        public void UpdateLevel(Level item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var level = db.Levels.Single(a => a.Id.Equals(item.Id));
                    level.Id = item.Id;
                    level.Name = item.Name;
                    level.Description = item.Description;
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// Delete a Level
        /// </summary>
        /// <param name="id"></param>
        public void DeleteLevel(int id)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var level = db.Levels.Single(a => a.Id.Equals(id));
                    db.Levels.DeleteOnSubmit(level);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// List all Level in database, order by Level's name
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Level> ListLevels(bool cacheEnabled = true)
        {
            if (cacheEnabled == true)
            {
                // if it's not in the cache, we need to read it form the repository// First, check the cache
                IEnumerable<Level> levelData = Cache.Get("levels") as IEnumerable<Level>;

                // if it's not in the cache, we need to read it form the repository
                if (levelData == null)
                {
                    //Get the repository data
                    try
                    {
                        using (var db = new ThuVienEPUDataContext())
                        {
                            db.DeferredLoadingEnabled = false;
                            levelData = db.Levels.OrderBy(a => a.Name).ToList();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Writer.Write(ex.Message, ex.Source);
                    }

                    if (levelData.Any())
                    {
                        Cache.Set("levels", levelData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                    }
                }
                return levelData;
            }
            else
            {
                //Get the repository data
                IEnumerable<Level> levelData = null;

                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        levelData = db.Levels.OrderBy(a => a.Name).ToList();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                return levelData;
            }
        }
        /// <summary>
        /// Get a Level if we know it's id
        /// </summary>
        /// <param name="id">id of the banner</param>
        /// <returns>
        /// return a banner
        /// </returns>
        public Level GetLevelById(int id)
        {
            Cache.Invalidate("level-" + id);
            Level levelData = Cache.Get("level-" + id) as Level;
            if (levelData == null)
            {
                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        levelData = db.Levels.Single(a => a.Id.Equals(id));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                if (levelData != null)
                {
                    Cache.Set("level-" + id, levelData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                }
            }
            return levelData;
        }
        /// <summary>
        /// check name of the level already exist in database 
        /// </summary>
        /// <param name="name"></param>
        /// <returns>
        /// return true if exist, else false
        /// </returns>
        public bool HasNameExisted(string name)
        {
            bool isExisted = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Levels
                                where a.Name.Equals(name)
                                select a.Id).ToList();
                    isExisted = list.Count > 0;
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isExisted;
        }

        /// <summary>
        /// check duplication of the banner in case of updating the banner
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool HasNameDuplicated(int id, string name)
        {
            bool isDuplicated = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Levels
                                where a.Name.Equals(name)
                                where !a.Id.Equals(id)
                                select a.Id).ToList();
                    isDuplicated = list.Count > 0;
                }
            }
            catch (Exception ex)
            {

                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isDuplicated;
        }

    }
}
